﻿'use strict';
var db = require('../utils/db');
var rooms = {};
var creatingRooms = {};
var userLocation = {};
var totalRooms = 0;
var constant = require('../utils/constant');
var log4js = require('log4js');
var log = log4js.getLogger("roommgr");

function generateRoomId() {
	var roomId = "";
	for (var i = 0; i < 6; ++i) {
		if (i == 0) {
			roomId = 1 + Math.floor(Math.random() * 9);
			roomId = roomId.toString();
		}
		else {
			roomId += (Math.floor(Math.random() * 10)).toString();
		}
	}
	return roomId;
}

function constructRoomFromDb(dbdata) {
	var roomInfo = {
		uuid: dbdata.uuid,
		id: dbdata.id,
		numOfGames: dbdata.num_of_turns,
		createTime: dbdata.create_time,
		nextButton: dbdata.next_button,
		conf: JSON.parse(dbdata.base_info),
		eachBankers: [],
		bcheckfinish: true,
	};
	roomInfo.conf.maxGames = dbdata.maxGames;
	var typeInfo = constant.CreateRoomInfo.type[roomInfo.conf.type];
	log.debug("1 room type == typeinfo == ", roomInfo.conf.type, typeInfo.file);
	roomInfo.gameMgr = require(typeInfo.file);
	roomInfo.seats = new Array(typeInfo.seatlen);

	var roomId = roomInfo.id;
	for (var i = 0; i < roomInfo.seats.length; ++i) {
		var seat = roomInfo.seats[i] = {};
		seat.userId = dbdata["user_id" + i];
		seat.score = dbdata["user_score" + i];
		seat.name = dbdata["user_name" + i];
		seat.ready = false;
		seat.isConfigPai = 0;
		seat.seatIndex = i;
		seat.roundScore = [];
		if (seat.userId > 0) {
			userLocation[seat.userId] = { roomId: roomId, seatIndex: i };
		}
	}
	rooms[roomId] = roomInfo;
	totalRooms++;
	return roomInfo;
}

exports.createRoom = function (creator, roomConf, gems, ip, port, callback) {
	console.log("room conf is ", roomConf);
	if (roomConf.type == null) {
		callback(1, null);
		return;
	}
	if (constant.CreateRoomInfo.paiNum[roomConf.paiNum] === undefined) {
		callback(1, null);
		return;
	}
	if (constant.CreateRoomInfo.type[roomConf.type] === undefined) {
		callback(1, null);
		return;
	}

	//判断房卡是否足够开房
	var roomManInfo = constant.CreateRoomInfo.type[roomConf.type];
	db.getRoomCostConfig(roomConf.type, constant.CreateRoomInfo.paiNum[roomConf.paiNum].jushu, function (ret1,ret2) {
		if (!ret2){
			console.log("not get cost config");
			return;
		}
		var cost = 0;
		if (roomConf.roomType == 1){
			cost = ret1 / roomManInfo.seatlen;
		} else {
			cost = ret1;
		}
		if(cost > gems){
			callback(2222,null);
			return;
		}

		var paiNum = constant.CreateRoomInfo.paiNum[roomConf.paiNum];
		var maxGames = paiNum.jushu;
		var fnCreate = function () {
			var roomId = generateRoomId();
			if (rooms[roomId] != null || creatingRooms[roomId] != null) {
				fnCreate();
			}
			else {
				creatingRooms[roomId] = true;
				db.is_room_exist(roomId, function (ret) {
					if (ret) {
						delete creatingRooms[roomId];
						fnCreate();
					}
					else {
						var createTime = Math.ceil(Date.now() / 1000);
						var roomInfo = {
							uuid: "",
							id: roomId,
							numOfGames: 0,
							createTime: createTime,
							nextButton: 0,
							seats: [],
							conf: {
								creator: creator,
								type: roomConf.type,
								paiNum: roomConf.paiNum,
								headNoType: roomConf.headNoType,
								roomType: roomConf.roomType,          //0--房主出 1--AA制收费开房
								specialPaiType: roomConf.specialPaiType,    //0--支持特殊牌型 1--无特殊牌型
								maiMa: roomConf.maiMa,             //0--不买码 1--买码
								selectPai: roomConf.selectPai,     //0--黑桃5 1--黑桃10 2--黑桃A
								daQiangRule: roomConf.daQiangRule,       //0--计分+1 1--计分*2
								zhuangMode: roomConf.zhuangMode,        //0--非庄家模式 1--庄家模式
								duoSe: roomConf.duoSe,             //0--无多色 1--多一色或多二色
								autoPeiPai: roomConf.autoPeiPai        //0--不自动配牌 1--5分钟自动配牌 
							},
							eachBankers: [],
							bcheckfinish: false,
							cost: cost
						};
						console.log("create room conf ", roomInfo.conf);
						var typeInfo = constant.CreateRoomInfo.type[roomInfo.conf.type];
						roomInfo.gameMgr = require(typeInfo.file);
						roomInfo.seats = new Array(typeInfo.seatlen);
						var seat_len = roomInfo.seats.length;
						for (var i = 0; i < seat_len; ++i) {
							roomInfo.seats[i] = {
								userId: 0,
								score: 0,
								isConfigPai: 0,
								name: "",
								ready: false,
								seatIndex: i,
								roundScore: [],
							};
						}
						roomInfo.nextButton = 0;

						//写入数据库
						db.create_room(roomInfo.id, roomInfo.conf, ip, port, maxGames, cost, createTime, typeInfo.seatlen, function (uuid) {
							delete creatingRooms[roomId];
							if (uuid != null) {
								roomInfo.uuid = uuid;
								roomInfo.conf.maxGames = maxGames;
								rooms[roomId] = roomInfo;
								totalRooms++;
								db.cost_gems(creator, cost);
								callback(0, roomId);
							}
							else {
								callback(3, null);
								log.warn("create room failed! user id = roomId = ", creator, roomId);
							}
						});
					}
				});
			}
		}

		fnCreate();
	});


};

exports.destroy = function (roomId) {
	var roomInfo = rooms[roomId];
	if (roomInfo == null) {
		return;
	}

	db.delete_room(roomId, function (ret) {
		if (ret) {
			var len = roomInfo.seats.length;
			for (var i = 0; i < len; ++i) {
				var userId = roomInfo.seats[i].userId;
				if (userId > 0) {
					delete userLocation[userId];
					db.set_room_id_of_user(userId, null);
				}
			}
			delete rooms[roomId];
			totalRooms--;
			log.debug("delete room ", roomId, rooms[roomId], totalRooms);
		}
	});
}

exports.getTotalRooms = function () {
	return totalRooms;
}

exports.getRoom = function (roomId) {
	return rooms[roomId];
};

exports.isCreator = function (roomId, userId) {
	var roomInfo = rooms[roomId];
	if (roomInfo == null) {
		return false;
	}
	return roomInfo.conf.creator == userId;
};

exports.enterRoom = function (roomId, userId, userName, callback) {
	var fnTakeSeat = function (room) {
		if (exports.getUserRoom(userId) == roomId) {
			return 0;
		}
		//坐下
		for (var i = 0; i < room.seats.length; ++i) {
			var seat = room.seats[i];
			if (seat == null) {
				seat = {};
				seat.seatIndex = i;
				seat.userId = userId;
				seat.name = userName;
				userLocation[userId] = { roomId: roomId, seatIndex: i };
				db.update_seat_info(roomId, i, seat.userId, "", seat.name);
				return 0;
			}
			else if (seat.userId <= 0) {
				seat.userId = userId;
				seat.name = userName;
				userLocation[userId] = { roomId: roomId, seatIndex: i };
				db.update_seat_info(roomId, i, seat.userId, "", seat.name);
				return 0;
			}
		}

		//房间已满
		return 1;
	}

	var room = rooms[roomId];
	if (room) {
		//坐下
		var ret = fnTakeSeat(room);
		callback(ret);
	}
	else {
		db.get_room_data(roomId, function (dbdata) {
			if (dbdata == null) {
				//找不到房间
				callback(2);
				log.warn('err: can not find the room data');
			}
			else {
				//服务器关闭后重启房间牌局继续,构造房间
				room = constructRoomFromDb(dbdata);

				//坐下
				var ret = fnTakeSeat(room);
				callback(ret);
			}
		});
	}
};


exports.setConfigPaiStatus = function (userId, status) {
	var roomId = exports.getUserRoom(userId);
	if (roomId == null) {
		return;
	}

	var room = exports.getRoom(roomId);
	if (room == null) {
		return;
	}

	var seatIndex = exports.getUserSeat(userId);
	if (seatIndex == null) {
		return;
	}

	var s = room.seats[seatIndex];
	s.isConfigPai = status;
}

exports.setReady = function (userId, value) {
	var roomId = exports.getUserRoom(userId);
	if (roomId == null) {
		return;
	}

	var room = exports.getRoom(roomId);
	if (room == null) {
		return;
	}

	var seatIndex = exports.getUserSeat(userId);
	if (seatIndex == null) {
		return;
	}

	var s = room.seats[seatIndex];
	s.ready = value;
}

exports.isReady = function (userId) {
	var roomId = exports.getUserRoom(userId);
	if (roomId == null) {
		return;
	}

	var room = exports.getRoom(roomId);
	if (room == null) {
		return;
	}

	var seatIndex = exports.getUserSeat(userId);
	if (seatIndex == null) {
		return;
	}

	var s = room.seats[seatIndex];
	return s.ready;
}


exports.getUserRoom = function (userId) {
	var location = userLocation[userId];
	if (location != null) {
		return location.roomId;
	}
	return null;
};

exports.getUserSeat = function (userId) {
	var location = userLocation[userId];
	//console.log(userLocation[userId]);
	if (location != null) {
		return location.seatIndex;
	}
	return null;
};

exports.getUserLocations = function () {
	return userLocation;
};

exports.exitRoom = function (userId) {
	var location = userLocation[userId];
	if (location == null)
		return;

	var roomId = location.roomId;
	var seatIndex = location.seatIndex;
	var room = rooms[roomId];
	delete userLocation[userId];
	if (room == null || seatIndex == null) {
		return;
	}

	var seat = room.seats[seatIndex];
	seat.userId = 0;
	seat.name = "";

	var numOfPlayers = 0;
	for (var i = 0; i < room.seats.length; ++i) {
		if (room.seats[i].userId > 0) {
			numOfPlayers++;
		}
	}

	if (numOfPlayers == 0) {
		exports.destroy(roomId);
	}

	db.set_room_id_of_user(userId, null);
};